import time
import random
from flask import Flask, jsonify, render_template, request
from threading import Thread, Lock
import numpy as np
from collections import deque
import time

app = Flask(__name__)

# 配置参数
SAMPLE_RATE = 1000  # 采样率 1000Hz
BUFFER_DURATION = 600  # 10分钟数据缓冲区
BUFFER_SIZE = BUFFER_DURATION * SAMPLE_RATE

# 数据缓冲区 - 使用双端队列提高性能
class DataBuffer:
    def __init__(self):
        self.buffer = deque(maxlen=BUFFER_SIZE)
        self.lock = Lock()
        self.start_time = time.time()
        
        # 初始化填充一些随机数据
        for _ in range(BUFFER_SIZE):
            self.add_sample((random.randint(0, 65535), random.randint(0, 65535)))
    
    def add_sample(self, sample):
        """添加新的采样点"""
        with self.lock:
            self.buffer.append(sample)
    
    def get_data_range(self, start_time, end_time, max_points=2000):
        """获取指定时间范围内的数据（降采样）"""
        with self.lock:
            # 计算起始和结束索引
            current_time = time.time()
            buffer_start_time = current_time - (len(self.buffer) / SAMPLE_RATE)
            
            # 确保请求的时间在缓冲区范围内
            start_time = max(start_time, buffer_start_time)
            end_time = min(end_time, current_time)
            
            # 计算索引位置
            start_idx = int((start_time - buffer_start_time) * SAMPLE_RATE)
            end_idx = int((end_time - buffer_start_time) * SAMPLE_RATE)
            
            # 获取数据切片
            data_slice = list(self.buffer)[start_idx:end_idx]
            
            # 降采样
            if len(data_slice) > max_points:
                step = max(1, len(data_slice) // max_points)
                data_slice = data_slice[::step]
            
            return data_slice

# 创建数据缓冲区
data_buffer = DataBuffer()

# 模拟数据接收线程
def data_receiver():
    """模拟从网络接收数据"""
    while True:
        # 模拟接收1000个采样点（实际应用中替换为真实数据接收）
        for _ in range(1000):
            ch1 = random.randint(0, 65535)
            ch2 = random.randint(0, 65535)
            data_buffer.add_sample((ch1, ch2))
        time.sleep(1)  # 每秒添加1000个点

# 启动数据接收线程
Thread(target=data_receiver, daemon=True).start()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/initial_data')
def get_initial_data():
    """获取初始显示数据（整个10分钟范围）"""
    current_time = time.time()
    start_time = current_time - BUFFER_DURATION
    data = data_buffer.get_data_range(start_time, current_time)
    return jsonify({
        'data': data,
        'time_range': [start_time, current_time]
    })

@app.route('/data')
def get_data():
    """获取指定时间范围的数据"""
    start_time = float(request.args.get('start', 0))
    end_time = float(request.args.get('end', time.time()))
    
    data = data_buffer.get_data_range(start_time, end_time)
    return jsonify({
        'data': data,
        'time_range': [start_time, end_time]
    })

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, threaded=True)